<template>
  <div class="auth-container no-footer">
    <!-- 左侧 Logo -->
    <div class="brand-section">
      <div class="brand-content">
        <h1 class="animate__animated animate__flip">MicroInvest</h1>
        <p class="brand-subtitle">智能投资的未来，从这里开始</p>
        <img src="@/assets/background.webp" alt="Logo" class="brand-logo" />
      </div>
    </div>

    <!-- 右侧表单 -->
    <div class="auth-section">
      <div class="auth-content">
        <div class="auth-header">
        <h2>创建账号</h2>
        <p class="subtitle">开始您的投资之旅</p>
        </div>

<!--      <el-steps :active="registerStep" finish-status="success" simple class="register-steps">-->
<!--        <el-step title="验证邮箱" />-->
<!--        <el-step title="设置账号" />-->
<!--      </el-steps>-->

      <!-- 邮箱验证步骤 -->
      <el-form
          v-if="registerStep === 1"
          :model="registerForm"
          :rules="registerRules"
          ref="registerFormStep1Ref"
      >
        <el-form-item prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" :prefix-icon="Message" />
        </el-form-item>
        <div class="form-actions">
          <el-button 
            type="primary" 
            class="submit-btn" 
            :disabled="isSubmitting"
            @click="handleEmailSubmit"
          >
            <template v-if="isSubmitting">
              <el-icon class="is-loading"><Loading /></el-icon>
              发送中...
            </template>
            <template v-else>
              下一步
            </template>
          </el-button>
        </div>
      </el-form>

      <!-- 设置账号步骤 -->
      <el-form
          v-else
          :model="registerForm"
          :rules="registerRules"
          ref="registerFormStep2Ref"
      >
        <el-form-item prop="userName">
          <el-input v-model="registerForm.userName" placeholder="设置用户名" :prefix-icon="User" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="设置密码"
              :prefix-icon="Lock"
              show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="确认密码"
              :prefix-icon="Lock"
              show-password
          />
        </el-form-item>
        <div class="form-actions">
          <el-button type="primary" class="submit-btn" @click="handleRegister">完成注册</el-button>
        </div>
      </el-form>

      <div class="auth-footer">
        已有账号？
        <el-button link type="primary" @click="goToLogin">登录</el-button>
      </div>
    </div>
  </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
// import '../../../../../node_modules/animate.css/animate.css';
import  'animate.css'
import { User, Lock, Message, Loading } from '@element-plus/icons-vue'
import { usersRegisterService, registerEmailService } from '@/api/user/users'
import {useTokenStore} from "@/stores/token";
import toast from "@/utils/toast";
const router = useRouter()
const route = useRoute()

// 注册步骤
const registerStep = ref(1)

// 两个表单的 ref
const registerFormStep1Ref = ref(null)
const registerFormStep2Ref = ref(null)


// 表单数据
const registerForm = reactive({
  userName: '',
  password: '',
  confirmPassword: '',
  email: '',
  code: '' // 验证码
})

const isSubmitting = ref(false)


onMounted(()=>{
  if(useTokenStore().hasToken){
    router.push('/center/findStock')
  }
});

// 表单验证规则
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能小于6位'))
  } else if (value.length > 20) {
    callback(new Error('密码长度不能超过20位'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormStep2Ref.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2到20个字符之间', trigger: 'blur' }
  ],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

// 完成注册
const handleRegister = () => {
  registerFormStep2Ref.value.validate(async (valid) => {
    if (valid) {
      try {
        const registerData = {
          userName: registerForm.userName,
          password: registerForm.password,
          email: registerForm.email
        }

        const { code, message } = await usersRegisterService(registerData)

        if (code === 200) {
          toast.success('注册成功')
          router.push('/user/auth')
        } else {
          toast.error(message || '注册失败')
        }
      } catch (error) {
        toast.error('注册失败，请稍后重试')
      }
    }
  })
}

// 去登录
const goToLogin = () => {
  router.push('/user/auth')
}

// 处理邮箱提交
const handleEmailSubmit = async () => {
  if (!registerForm.email) {
    toast.warning('请输入邮箱')
    return
  }

  try {
    isSubmitting.value = true
    const { code, message } = await registerEmailService(registerForm.email)
    
    if (code === 200) {
      toast.success('验证码已发送')
      // 跳转到验证码页面
      router.push({
        path: '/user/email-verification',
        query: { email: registerForm.email }
      })
    } else {
      toast.error(message || '发送失败')
    }
  } catch (error) {
    toast.error('发送失败，请稍后重试')
  } finally {
    isSubmitting.value = false
  }
}

// 修改 onMounted 钩子
onMounted(() => {
  // 检查是否从验证码页面返回
  const verified = route.query.verified
  const email = route.query.email
  
  if (verified && email) {
    registerForm.email = email
    registerStep.value = 2
  }
})
</script>

<style lang="scss" scoped>
@import '../../../assets/styles/theme/auth';

</style>
